package org.jeecg.modules.wlhy.hydriverbank.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.modules.third.aliyunocr.AliyunOcrService;
import org.jeecg.modules.wlhy.hydriverbank.entity.HyDriverBank;
import org.jeecg.modules.wlhy.hydriverbank.mapper.HyDriverBankMapper;
import org.jeecg.modules.wlhy.hydriverbank.service.IHyDriverBankService;
import org.jeecg.modules.wlhy.utils.BankTypeUtil;
import org.jeecg.modules.wlhy.utils.HyCfgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description: 司机银行卡信息
 * @Author: duanlikao
 * @Date:   2020-12-14
 * @Version: V1.0
 */
@Service
public class HyDriverBankServiceImpl extends ServiceImpl<HyDriverBankMapper, HyDriverBank> implements IHyDriverBankService {

    @Resource
    private HyDriverBankMapper driverBankMapper ;

    @Autowired
    private AliyunOcrService aliyunOcrService;

    //    @Resource
//    private  AliyunOcrHyDriverBankMapperService aliyunOcrService;
//
//    private static final Logger LOGGER = LoggerFactory.getLogger(HyDriverBankServiceImpl.class);


//    @Override
//    public Result <?>  saveDriverBank(HyDriverBank hyDriverBank){
//

//        Result<JSONObject> result = new Result<JSONObject>();
//        if(StringUtils.isNotEmpty(hyDriverBank.getBankNum())){
//            hyDriverBank.setBankNum(
//                    hyDriverBank.getBankNum().replaceAll(" ","")
//            );
//        }
//
//
//        HyDriverBank hyDriverBankDb = null;
//        if(StringUtils.isNotEmpty(hyDriverBank.getId()) ){
//            hyDriverBankDb = getById(hyDriverBank.getId());
//            if(hyDriverBankDb==null) {
//                throw new JeecgBootException("未找到对应数据");
//            }
//        }
//
//        //辽宁税务需要 start
////        if(StringUtils.isEmpty(hyDriverBank.getBankImgFront())){
////            throw new JeecgBootException("请上传银行卡正面照片！");
////        }
//        //辽宁税务需要 end
//
//        if( StringUtils.isEmpty(hyDriverBank.getIdcard())){
//            throw new JeecgBootException("请填写身份证号！");
//        }
//
//        if(hyDriverBank.getIdcard() != null &&  hyDriverBank.getIdcard().length() != 15 &&
//                hyDriverBank.getIdcard().length() != 18){
//            throw new JeecgBootException("身份证应为15位或者18位。");
//        }
//        if(!IDUtils.isIDNumber(hyDriverBank.getIdcard())){
//            throw new JeecgBootException("请填写正确身份证！");
//        }
//
//        String bankInfo  = aliyunOcrService.ToolsBank(hyDriverBank.getIdcard(),
//                hyDriverBank.getBankName(),hyDriverBank.getBankNum());
//        String bankName = "";
//        if(StringUtils.isNotEmpty(bankInfo)) {
//            JSONObject jsonObject = JSONObject.parseObject(bankInfo);
//            String status = jsonObject.get("status") != null ? jsonObject.get("status").toString() : "";
//            if(StringUtils.isNotEmpty(status)  && !status.equals("01")){
//                //jsonObject.get("msg").toString()
//                return Result.error("请重新输入开卡姓名，开卡身份证号，开卡银行卡号！");
//            }
//
//            if(StringUtils.isNotEmpty(status)  && status.equals("01")){
//                bankName = jsonObject.get("bank").toString();
//            }
//        }
//        if(StringUtils.isEmpty(bankName)){
//            return Result.error("获取开户行信息失败,请稍后再试或者联系客服！");
//        }
//
//       String bankType = BankTypeUtil.getBankType(bankName);
//        if(StringUtils.isEmpty(bankType)){
//            return Result.error("暂不支持改银行！");
//        }
//        hyDriverBank.setBankType(bankType);
//
//        HyDriverBank querydriverBank  =  this.getByBankNumAndDriverId(hyDriverBank.getDriverId(),hyDriverBank.getBankNum()) ;
//
//        hyDriverBank.setIzUsed("1");
//        boolean resultSave = false;
//        if(querydriverBank != null ){
//             hyDriverBank.setId(querydriverBank.getId());
//             resultSave = updateById(hyDriverBank);
//        }else{
//            resultSave =  save(hyDriverBank);
//        }
//
//        result.setSuccess(false);
//        result.setCode(CommonConstant.REGISTER_FAILED);
//        result.setMessage("司机银行卡信息保存失败,请重新提交信息！");
//        result.setTimestamp((new Date()).getTime());
//        if(resultSave){
//            result.setSuccess(true);
//            result.setCode(CommonConstant.SC_OK_200);
//            result.setMessage("司机银行卡信息保存成功!");
//            result.setResult( hyDriverBankDb == null ?
//                    JSONObject.parseObject(JSONObject.toJSONString(hyDriverBank) ):
//                    JSONObject.parseObject(JSONObject.toJSONString(hyDriverBankDb) )
//            );
//        }
//        return result;
//    }

    @Override
    public  HyDriverBank getByBankNumAndDriverId(String driverId, String bankNum){
        LambdaQueryWrapper <HyDriverBank> queryWrapper = new LambdaQueryWrapper <>();
        queryWrapper.eq(HyDriverBank::getDriverId,driverId);
        queryWrapper.eq(HyDriverBank::getBankNum,bankNum);
        return  getOne(queryWrapper);
    }

    @Override
    public List<HyDriverBank> getByDriverId(String driverId){
        LambdaQueryWrapper <HyDriverBank> queryWrapper = new LambdaQueryWrapper <>();
        queryWrapper.eq(HyDriverBank::getDriverId,driverId);
        List<HyDriverBank> listDriverBank = this.list(queryWrapper);
        return listDriverBank;
    }
    //获得司机本人银行卡
    @Override
    public HyDriverBank getDriverSelfBank(String driverId){
        LambdaQueryWrapper <HyDriverBank> queryWrapper = new LambdaQueryWrapper <>();
        //queryWrapper.eq( HyDriverBank::getBankName, driverName);
        queryWrapper.eq(HyDriverBank::getDriverId, driverId);
        List<HyDriverBank> hyDriverBankList = list(queryWrapper);
        if (CollUtil.isEmpty(hyDriverBankList)) {
            return null;
        }
        return hyDriverBankList.get(0);
    }

    /**
     * 司机银行卡解绑
     * @param id
     * @return
     */
    @Override
    public Result <?> unBundLing(String id){
        if(StringUtils.isEmpty(id)){
            return Result.error("id不能为空");
        }
        HyDriverBank hyDriverBankDb = this.getById(id);;
        if(hyDriverBankDb==null) {
            return Result.error("未找到对应数据");
        }
        hyDriverBankDb.setIzUsed("0");
        this.updateById(hyDriverBankDb);
        return Result.OK("解绑成功!");
    }

    @Override
    public Result<?> addDriverBank(HyDriverBank hyDriverBank) {
        String bankName = hyDriverBank.getBankName();
        if(StringUtils.isBlank(bankName)){
            return Result.error("姓名不能为空");
        }
        String bankNum = hyDriverBank.getBankNum();
        if(StringUtils.isBlank(bankNum)){
            return Result.error("银行卡号不能为空");
        }

        bankName = bankName.trim();
        bankNum = bankNum.trim();
        hyDriverBank.setBankName(bankName);
        hyDriverBank.setBankNum(bankNum);

        if(HyCfgUtil.isUsed2("checkBankCard")){
            String idcard = hyDriverBank.getIdcard();
            //验证银行卡三要素
            Result<?> result = aliyunOcrService.ToolsBank(idcard, bankName, bankNum);
            if(!result.isSuccess()){
                return result;
            }
            JSONObject ret = (JSONObject) result.getResult();
            String bank = ret.getString("bank");
            String bankType = BankTypeUtil.getBankTypeByBankName2(bank);
            if(StringUtils.isEmpty(bankType)){
                return Result.error("未找到对应的银行卡类别,请联系管理员,银行名称:" + bank);
            }
            hyDriverBank.setBankType(bankType);
        } else {
            String bankType = hyDriverBank.getBankType();
            if(StringUtils.isEmpty(bankType)){
                return Result.error("银行类别不能为空");
            }
            if(!BankTypeUtil.checkBankType(bankType)){
                return Result.error("银行类别错误");
            }
        }

        String driverId = hyDriverBank.getDriverId();
        int count = this.getDriverBankCountByDriverId(driverId);
        if(count == 0){
            //设置为默认收款账号
            hyDriverBank.setIzDefault("1");
        } else {
            //Modified start at 2024-10-28 for 如果另外新增的银行卡设置成默认银行卡，需要取消该司机其它银行卡的默认设置
            if ("1".equals(hyDriverBank.getIzDefault())) {
                List<HyDriverBank> driverBanks = this.list(new LambdaQueryWrapper<HyDriverBank>().eq(HyDriverBank::getDriverId, driverId));
                if (CollUtil.isNotEmpty(driverBanks)) {
                    for (HyDriverBank bank : driverBanks) {
                        bank.setIzDefault("0");
                    }
                    this.updateBatchById(driverBanks);
                }
            }
            //Modified end at 2024-10-28

            HyDriverBank querydriverBank = this.getByBankNumAndDriverId(driverId,bankNum);
            if(querydriverBank != null){
                hyDriverBank.setId(querydriverBank.getId());
                hyDriverBank.setDelFlag("0"); //添加重复的银行卡把删除标记去掉
                this.updateById(hyDriverBank);
                return Result.OK("添加成功!");
            }
        }
        this.save(hyDriverBank);
        return Result.OK("添加成功!");
    }

    @Override
    @CacheEvict(value = CacheConstant.SYS_DICT_TABLE_CACHE ,key = "'SimpleKey [hy_driver_bank,bank_num,id,' + #hyDriverBank.id + ']'")
    public Result<?> updateDriverBank(HyDriverBank hyDriverBank) {
        String bankName = hyDriverBank.getBankName();
        if (StringUtils.isBlank(bankName)) {
            return Result.error("姓名不能为空");
        }
        String bankNum = hyDriverBank.getBankNum();
        if (StringUtils.isBlank(bankNum)) {
            return Result.error("银行卡号不能为空");
        }

        bankName = bankName.trim();
        bankNum = bankNum.trim();

        if (HyCfgUtil.isUsed2("checkBankCard")) {
            String idcard = hyDriverBank.getIdcard();
            //验证银行卡三要素
            Result<?> result = aliyunOcrService.ToolsBank(idcard, bankName, bankNum);
            if (!result.isSuccess()) {
                return result;
            }
//            JSONObject ret = (JSONObject) result.getResult();
//            String bank = ret.getString("bank");
//            String bankType = BankTypeUtil.getBankTypeByBankName2(bank);
//            if (StringUtils.isEmpty(bankType)) {
//                return Result.error("未找到对应的银行卡类别,请联系管理员,银行名称:" + bank);
//            }
//            hyDriverBank.setBankType(bankType);
        } else {
            String bankType = hyDriverBank.getBankType();
            if (StringUtils.isEmpty(bankType)) {
                return Result.error("银行类别不能为空");
            }
            if (!BankTypeUtil.checkBankType(bankType)) {
                return Result.error("银行类别错误");
            }
        }

        hyDriverBank.setBankName(bankName);
        hyDriverBank.setBankNum(bankNum);
        this.updateById(hyDriverBank);
        return Result.OK("修改成功!");
    }

    @Override
    public int getDriverBankCountByDriverId(String driverId) {
        int count = this.count(new QueryWrapper<HyDriverBank>().eq("driver_id", driverId).eq("iz_used","1"));
        return count;
    }

    @Override
    @Transactional
    public Result<?> setDefault(HyDriverBank driverBank) {
        String driverId = driverBank.getDriverId();
        List<HyDriverBank> driverBanks = this.list(new QueryWrapper<HyDriverBank>().eq("driver_id", driverId));
        if(driverBanks.size() != 0){
            for (HyDriverBank bank : driverBanks) {
                bank.setIzDefault("0");
            }
            this.updateBatchById(driverBanks);
        }
        driverBank.setIzDefault("1");
        this.updateById(driverBank);
        return Result.OK("设置成功!");
    }

    @Override
    public List<HyDriverBank> getDriverBankByDriverId(String driverId) {
        return this.list(new QueryWrapper<HyDriverBank>().eq("driver_id", driverId).eq("iz_used","1"));
    }

    @Override
    public HyDriverBank getDefaultDriverBank(String driverId) {
        List<HyDriverBank> list = this.list(new QueryWrapper<HyDriverBank>()
                .eq("driver_id", driverId)
                .eq("iz_default", "1")
                .eq("iz_used","1"));

        if(list.size() == 0){
            return null;
        }
        return list.get(0);
    }

    @Override
    public int getBankNumsByDriverId(String driverId) {
        return this.count(new QueryWrapper<HyDriverBank>().eq("driver_id" ,driverId).eq("iz_used","1"));
    }

   @Override
   public HyDriverBank getDriverBankInfo(String driverId , String bankNum){
      return driverBankMapper.getDriverBankInfo(driverId , bankNum);
    }

    @Override
    public IPage<HyDriverBank> pageList(Page<HyDriverBank> page, QueryWrapper<HyDriverBank> queryWrapper, String customerId) {
        return page.setRecords(baseMapper.pageList(page, queryWrapper,customerId));
    }
}
